import dayjs from "dayjs"
import { useIntersectionObserver } from '@vueuse/core'

// 格式化秒数
export const formatTimePlugin = {
  install(app) {
    app.directive('format-time', (el, binding) => {
      let minute = Math.floor(binding.value / 60)
      let second = Math.floor(binding.value - (minute * 60))
      minute = minute < 10 ? '0' + minute : minute
      second = second < 10 ? '0' + second : second
      el.innerHTML = minute + ':' + second
    })
  }
}

// 格式化毫秒数
export const formatMillisecPlugin = {
  install(app) {
    app.directive('format-millisec', (el, binding) => {
      const durationStr = binding.value.toString()
      const duration = durationStr.substring(0, durationStr.length - 3)
      let minute = Math.floor(duration / 60)
      let second = Math.floor(duration - (minute * 60))
      minute = minute < 10 ? '0' + minute : minute
      second = second < 10 ? '0' + second : second
      el.innerHTML = minute + ':' + second
    })
  }
}

// 格式化播放总数
export const formatPlyCountPlugin = {
  install(app) {
    app.directive('format-play-count', (el, binding) => {
      const count = binding.value.toString()
      if (count.length < 5) {
        el.innerHTML = count
      } else if (count.length > 4 && count.length < 9) {
        el.innerHTML = (Number(count) / 10000).toFixed(1) + '万'
      } else {
        el.innerHTML = (Number(count) / 100000000).toFixed(2) + '亿'
      }
    })
  }
}

// 格式化 unix 时间戳
export const unixFormat = {
  install(app) {
    app.directive('unix-format', (el, binding) => {
      el.innerHTML = dayjs(binding.value).format('YYYY-MM-DD HH:mm')
    })
  }
}

// 图片懒加载
export const lazyImage = {
  install(app) {
    app.directive('lazy-image', (el, binding) => {
      const { stop } = useIntersectionObserver(
        el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            el.src = binding.value
            stop()
          }
        }
      )
    })
  }
}